/**
 *  @author Cornelius Huang
 *  Onsite Item one line
 */
app.directive('siteItem', [function() {
	return {
		restrict: 'AE',
		transclude: false,
		templateUrl: './views/siteItem.html',
		scope: {
			country: '<?',
			flexibility: '=?',
			durChange: '&?'
		},
		controller: ['$rootScope', '$scope', function($rootScope, $scope) {
			this.$onInit = function() {
				//console.log($rootScope.userInfo);
				//console.log($scope.flexibility);
				console.log('on Init');
				$scope.duration = getDuration($scope.country.name);
				$scope.aflex = getAflex($scope.country.name);
			}
			
			$scope.iptDoChange = function() {
				//console.log($scope.duration);
				//console.log($scope.aflex);
				console.log($rootScope.userInfo);
				var duration = $scope.duration;
				var flexibility = {
					id: null,
					username: null,
					fullName: null,
					country: null,
					duration: null
				}
				if($scope.aflex != null) {
					flexibility = $scope.aflex;
					//TODO: duration modify & validate push or not
					//console.log(flexibility);
					//console.log(duration);
					if(duration != null) {
						flexibility.duration = duration.toString();
					} else {
						flexibility.duration = duration;
					}
					$scope.durChange({flex: flexibility});
				} else {
					flexibility.username = $rootScope.userInfo.userName;
					flexibility.country = $scope.country.name;
					//console.log(flexibility);
					//TODO: duration modify & validate push or not
					//console.log(duration);
					if(duration != null) {
						flexibility.duration = duration.toString();
					} else {
						flexibility.duration = duration;
					}
					$scope.durChange({flex: flexibility});
				}
			}
			
			var getAflex = function(country) {
				var aflex = null;
				$scope.flexibility.forEach(function(flex) {
					if(flex.country === country) {
						aflex = flex;
					}
				});
				return aflex;
			}
			
			var getDuration = function(country) {
				var duration = null;
				$scope.flexibility.forEach(function(flex) {
					if(flex.country === country) {
						//console.log(duration);
						duration = Number.parseInt(flex.duration);
					}
				});
				return duration;
			}
			
		}]
	}
}]);